package com.imooc.product.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

/**
 * @author Jiayuan
 * @version 1.0
 * @description:
 * @time 2018/8/2 20:57
 */
public class JsonUtil {

    @Autowired
    private static ObjectMapper objectMapper;

    /**
     * 对象转json
     * @param object
     * @return
     */
    public static String toJSON(Object object){
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setPrettyPrinting();
        Gson gson = gsonBuilder.create();
        return gson.toJson(object);
    }

    /**
     * json转对象
     * @param string
     * @param classType
     * @return
     */
    public static Object fromObject(String string, Class classType){
        try{
            return objectMapper.readValue(string,classType);
        }catch(IOException e){
            e.printStackTrace();
        }
        return null;
    }
}
